package net.libra.loader
{
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.URLRequest;
	import flash.system.ApplicationDomain;
	import flash.system.LoaderContext;
	import flash.utils.Dictionary;
	
	/**
	 * 队列加载swf放进当前域
	 * @author elvisjiang
	 */
	public class SwfLoader extends EventDispatcher
	{
		public static var gameSwfLoadedDict:Dictionary = new Dictionary();
		public static var VERSION:String;
		private var swfList:Array;
		private var loader:Loader;
		
		public function SwfLoader()
		{
			this.swfList = [];
			this._currentIndex = -1;
		}
		
		public function addURL(url:String):void
		{
			for(var i:int = 0;i<swfList.length;i++)
			{
				if(swfList[i] == url)
				{
					return;
				}
			}
			if(gameSwfLoadedDict[url] == true)
			{
				return;
			}
			this.swfList.push(url);
		}
		
		public function addURLArray(arry:Array):void
		{
			for(var i:int = 0;i<arry.length;i++)
			{
				if(!gameSwfLoadedDict[arry[i]] || gameSwfLoadedDict[arry[i]] == false)
				{
					this.swfList.push(arry[i]);
				}
			}
		}
		/**
		 * 是否loaded
		 * @param arry ["a.swf","b.swf"]
		 * @return 
		 * 
		 */		
		public static function isLoaded(arry:Array):Boolean
		{
			var result:Boolean = false;
			for(var i:int = 0;i<arry.length;i++)
			{
				if(gameSwfLoadedDict[arry[i]] == true)
				{
					result = true;
				}else{
					result = false;
				}
			}
			return result;
		}
		
		public function start():void
		{
			_totalSwfNum = swfList.length;
			if(this._currentIndex == -1)
			{
				this.run();
			}
		}
		private function run():void
		{
			this._currentIndex ++;
			var url:String = this.swfList[this._currentIndex];
			if(url && url != "")
			{
				loader = new Loader();
				var context:LoaderContext = new LoaderContext(false,ApplicationDomain.currentDomain);
				loader.contentLoaderInfo.addEventListener(Event.COMPLETE,__onResult);
				loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,__onResult);
				loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS,__onResult);
				
				loader.load(new URLRequest(url + "?vesion = "+VERSION),context);
				
			}else{
//				trace("-----------------test................swf Loader");
				_currentIndex = -1;
				this.dispatchEvent(new LoaderEvent(LoaderEvent.ON_COMPLETE));
				Log.info("[SwfLoader] AllItemsLoaded");
			}
		}
		private function __onResult(event:Event):void
		{
			var contentLoaderInfo:LoaderInfo = event.target as LoaderInfo;
			if(event.type == IOErrorEvent.IO_ERROR)
			{
				this.dispatchEvent(new LoaderEvent(LoaderEvent.ON_FAILURE));
				this._currentIndex = -1;
				gameSwfLoadedDict[this.swfList[this._currentIndex]] = false;
				finalizeLoader();
				throw new Error("路径有错，检查下URL");
				Log.error("[SwfLoader] 路径有错，检查下URL");
			}else if(event.type == Event.COMPLETE )
			{
				Log.info("[SwfLoader] Loaded "  + this.swfList[this._currentIndex]);
				gameSwfLoadedDict[this.swfList[this._currentIndex]] = true;
//				trace("onCompelete:",_currentIndex);
				finalizeLoader();
				this.run();
			}else if(event.type == ProgressEvent.PROGRESS)
			{
				_currentSwfLoadedBytes = (contentLoaderInfo.bytesLoaded/1000).toFixed(1);
				_currentSwfTotalbytes = (contentLoaderInfo.bytesTotal/1000).toFixed(1);
				
				data.currentIndex = _currentIndex+1;
				data.totalSwfNum = _totalSwfNum;
				data.currentSwfLoadedBytes = _currentSwfLoadedBytes;
				data.currentSwfTotalBytes = _currentSwfTotalbytes;
				data.percent = int(100 * (contentLoaderInfo.bytesLoaded / contentLoaderInfo.bytesTotal));
				
//				_loadState = _currentIndex+1 +"/"+_totalSwfNum+"_"+_currentSwfLoadedBytes+"k/"+_currentSwfTotalbytes+"k";
				dispatchEvent(new LoadEvent(LoaderEvent.ON_PROGRESS,{state:data}));
			}
		}
		private var data:Object = {};
		private var _loadState:String;
		private function finalizeLoader():void
		{
			loader.contentLoaderInfo.removeEventListener(Event.COMPLETE,__onResult);
			loader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR,__onResult);
			loader.contentLoaderInfo.removeEventListener(ProgressEvent.PROGRESS,__onResult);
			loader = null;
		}
		
		private var _totalSwfNum:uint;
		private var _currentIndex:int;
		private var _currentSwfLoadedBytes:String;
		private var _currentSwfTotalbytes:String;
	}
}